#!/bin/sh

if [ ! -d /var/www/cgj_erp/runtime ]; then
    mkdir -p /var/www/cgj_erp/runtime && chown -R www:www /var/www/cgj_erp && chmod -R 775 /var/www/cgj_erp
fi

cd /var/www/cgj_erp

echo "---------------APP_ENV: $APP_ENV-----------------"

# 计算当前composer文件的hash
CURRENT_HASH=$(sha256sum composer.json composer.lock 2>/dev/null | sha256sum)

# 读取保存的hash（如果存在）
SAVED_HASH_FILE=/var/www/cgj_erp/runtime/.composer.hash
SAVED_HASH=$(cat $SAVED_HASH_FILE 2>/dev/null || echo "")

# 比较hash值
if [ "$CURRENT_HASH" != "$SAVED_HASH" ]; then
    echo "Composer files changed, running install..."
    if [ "$APP_ENV" = "prod" ]; then
        composer install --no-dev -o --no-progress --no-interaction
    else
        composer install -o --no-progress --no-interaction
    fi

    # 保存新的hash值
    echo "$CURRENT_HASH" > $SAVED_HASH_FILE
else
    echo "Composer files unchanged, skipping install."
fi

if [ -x /usr/bin/supervisord ]; then
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] supervisord working"
    exec /usr/bin/supervisord -n -c /etc/supervisord.conf;
else
  if [ "$ERP_HYPERF_WATCHER" = "true" ] && [ "$APP_ENV" = "dev" ]; then
      echo "[$(date '+%Y-%m-%d %H:%M:%S')] hyperf watcher working"
      exec php /var/www/cgj_erp/bin/hyperf.php server:watch;
  else
      echo "[$(date '+%Y-%m-%d %H:%M:%S')] hyperf start working"
      exec php /var/www/cgj_erp/bin/hyperf.php start;
  fi
fi